package com.lzq.mq.nameserver.common;

import com.lzq.mq.common.dto.NodeAckDTO;
import com.lzq.mq.common.dto.SlaveAckDTO;
import com.lzq.mq.nameserver.core.PropertiesLoader;
import com.lzq.mq.nameserver.replication.ReplicationTask;
import com.lzq.mq.nameserver.store.ReplicationChannelManager;
import com.lzq.mq.nameserver.store.ReplicationMsgQueueManager;
import com.lzq.mq.nameserver.store.ServiceInstanceManager;
import io.netty.channel.Channel;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicBoolean;

@Slf4j
public class CommonCache {

    @Getter
    private static PropertiesLoader properties;

    @Getter
    private static ServiceInstanceManager serviceInstanceManager;

    /**
     * nameserver配置
     */
    @Getter
    @Setter
    private static NameserverProperties nameserverProperties;

    /**
     * 存储需要同步的子节点channel
     * ChannelManager用于管理需要同步的子节点, 存储的key为子节点的ip:port, value为对应的channel
     */
    @Getter
    private static ReplicationChannelManager replicationChannelManager = new ReplicationChannelManager();

    @Getter
    @Setter
    private static ReplicationTask replicationTask;

    @Setter
    @Getter
    private static Channel masterConnection = null;

    /**
     * 是否连接到集群的上游节点
     */
    @Getter
    private static AtomicBoolean isConnectedReplicationServer = new AtomicBoolean(false);

    /**
     * 存储需要同步的子节点的消息队列
     */
    @Getter
    private static ReplicationMsgQueueManager replicationMsgQueueManager = new ReplicationMsgQueueManager();

    @Getter
    private static Map<String, SlaveAckDTO> ackMap = new ConcurrentHashMap<>();

    public static void init() {

        try {
            properties = new PropertiesLoader();
            properties.loadProperties();
            log.info("nameserver配置加载成功{}",  properties);

            serviceInstanceManager = new ServiceInstanceManager();
        } catch (IOException e) {
            log.error("导入nameserver配置时出错", e);
        }
    }

}
